package com.mdd.front.service.impl;

import cn.dev33.satoken.SaManager;
import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.*;
import com.alipay.api.response.*;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Assert;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mdd.car.entity.CarBrand;
import com.mdd.car.mapper.CarBrandMapper;
import com.mdd.common.base.page.PageValidate;
import com.mdd.common.core.PageResult;
import com.mdd.common.entity.AlipayRoyaltyAccountInfo;
import com.mdd.common.entity.AlipayTradePayInfo;
import com.mdd.common.entity.OrderBillInfo;
import com.mdd.common.entity.agreement.AlipayAuthOrderFreeze;
import com.mdd.common.entity.agreement.RiskControl;
import com.mdd.common.entity.car.CarOrderDetail;
import com.mdd.common.entity.car.CarOrderInfoListed;
import com.mdd.common.entity.order.*;
import com.mdd.common.entity.order.OrderItem;
import com.mdd.common.entity.user.UserAuth;
import com.mdd.common.enums.OrderEnum;
import com.mdd.common.enums.order.status.LeaseOrderStatusEnum;
import com.mdd.common.enums.order.status.OrderVehicleStatusEnum;
import com.mdd.common.enums.order.status.RentOrderStatusEnum;
import com.mdd.common.enums.order.type.OrderTypeEnum;
import com.mdd.common.enums.pay.TradePayStatusEnum;
import com.mdd.common.mapper.AlipayRoyaltyAccountInfoMapper;
import com.mdd.common.mapper.AlipayTradePayInfoMapper;
import com.mdd.common.mapper.auth.AlipayAuthOrderFreezeMapper;
import com.mdd.common.mapper.bill.OrderBillInfoMapper;
import com.mdd.common.mapper.order.*;
import com.mdd.common.mapper.risk.RiskControlMapper;
import com.mdd.common.mapper.user.UserAuthMapper;
import com.mdd.common.util.TimeUtils;
import com.mdd.front.LikeFrontThreadLocal;
import com.mdd.front.service.IUserOrderService;
import com.mdd.front.service.order.OrderBillInfoService;
import com.mdd.front.validate.car.order.CarOrderCreateValidate;
import com.mdd.front.validate.order.OrderClueCreateValidate;
import com.mdd.front.validate.order.OrderCreateValidate;
import com.mdd.front.vo.car.CarOrderDetailVo;
import com.mdd.front.vo.car.CarOrderInfoListedVo;
import com.mdd.front.vo.order.*;
import com.mdd.front.vo.sku.ProductSkuVo;
import com.mdd.front.vo.spu.ProductSpuVo;
import com.mdd.product.entity.LeasingScheme;
import com.mdd.product.entity.LeasingSchemeDetails;
import com.mdd.product.entity.ProductSku;
import com.mdd.product.entity.ProductSpu;
import com.mdd.product.mapper.LeasingSchemeDetailsMapper;
import com.mdd.product.mapper.LeasingSchemeMapper;
import com.mdd.product.mapper.ProductSkuMapper;
import com.mdd.product.mapper.ProductSpuMapper;
import com.mdd.service.pay.AlipayTradeOrderService;
import com.mdd.store.entity.Store;
import com.mdd.store.mapper.StoreMapper;
import com.mdd.vo.pay.TradePayInfo;
import org.apache.commons.lang.time.DateUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * {@code @Description}
 * {@code @Author} 幻速
 * {@code @Date} 2023/11/1 18:59
 **/
@Service
public class UserOrderServiceImpl implements IUserOrderService {
    @Resource
    OrderBillInfoService orderBillInfoService;
    @Resource
    OrderInfoMapper orderInfoMapper;
    @Resource
    AuthOrderServiceImpl authOrderService;
    @Resource
    OrderItemMapper orderItemMapper;
    @Resource
    OrderClueMapper orderClueMapper;
    @Resource
    OrderLeaseDetailsMapper orderLeaseDetailsMapper;
    @Resource
    AlipayAuthOrderFreezeMapper alipayAuthOrderFreezeMapper;
    @Resource
    OrderBillInfoMapper orderBillInfoMapper;
    @Resource
    PreAuthorizationPaymentRecordMapper preAuthorizationPaymentRecordMapper;
    @Resource
    StoreMapper storeMapper;
    @Resource
    RiskControlMapper riskControlMapper;
    @Resource
    LeasingSchemeDetailsMapper leasingSchemeDetailsMapper;
    @Resource
    LeasingSchemeMapper leasingSchemeMapper;
    @Resource
    ProductSkuMapper productSkuMapper;
    @Resource
    ProductSpuMapper productSpuMapper;

    @Resource
    DefaultAlipayClient defaultAlipayClient;
    @Resource
    DefaultAlipayClient defaultAlipayWapClient;
    @Resource
    AlipayTradeOrderService alipayTradeOrderService;
    @Resource
    AlipayTradePayInfoMapper alipayTradePayInfoMapper;
    @Resource
    UserAuthMapper userAuthMapper;
    @Resource
    AlipayRoyaltyAccountInfoMapper alipayRoyaltyAccountInfoMapper;

    @Resource
    CarBrandMapper carBrandMapper;

    @Override
    public PageResult<OrderInfoListedVo> list(Integer status, PageValidate pageValidate) {
        Integer page  = pageValidate.getPageNo();
        Integer limit = pageValidate.getPageSize();
        LambdaQueryWrapper<OrderInfo> orderInfoWrapper = new LambdaQueryWrapper<>();
        orderInfoWrapper.eq(OrderInfo::getUserId, SaManager.getStpLogic("user").getLoginId());
        orderInfoWrapper.orderByDesc(OrderInfo::getId);
        if(Objects.nonNull(status)){
            orderInfoWrapper.eq(OrderInfo::getStatus,status);
        }
        IPage<OrderInfo> orderInfoList = orderInfoMapper.selectPage(new Page<>(page, limit), orderInfoWrapper);
        List<OrderInfoListedVo> orderInfoListedVos = new ArrayList<>();
        orderInfoList.getRecords().forEach(orderInfo -> {
            OrderInfoListedVo orderInfoListedVo = new OrderInfoListedVo();
            BeanUtils.copyProperties(orderInfo, orderInfoListedVo);

            OrderItemVo orderItemVo = new OrderItemVo();
            OrderItem orderItem = orderItemMapper.selectOne(new LambdaQueryWrapper<OrderItem>().eq(OrderItem::getOrderId,orderInfo.getId()).last("limit 1"));
            if(Objects.nonNull(orderItem)) {
                BeanUtils.copyProperties(orderItem, orderItemVo);
                orderInfoListedVo.setOrderItem(orderItemVo);
            }
            OrderLeaseDetails orderLeaseDetails = orderLeaseDetailsMapper.selectOne(new LambdaQueryWrapper<OrderLeaseDetails>().eq(OrderLeaseDetails::getOrderId,orderInfo.getId()).last("limit 1"));
            if(Objects.nonNull(orderLeaseDetails)){
                OrderLeaseDetailsDetailVo leaseDetailsDetailVo = new OrderLeaseDetailsDetailVo();
                BeanUtils.copyProperties(orderLeaseDetails, leaseDetailsDetailVo);
                orderInfoListedVo.setLeaseDetailsDetail(leaseDetailsDetailVo);
            }

            orderInfoListedVos.add(orderInfoListedVo);
        });
        return PageResult.iPageHandle(orderInfoList.getTotal(), orderInfoList.getCurrent(), orderInfoList.getSize(), orderInfoListedVos);
    }
    @Override
    @Transactional
    public OrderInfoDetailVo detail(Long orderId) {
        OrderInfo orderInfo = orderInfoMapper.selectById(orderId);

        Assert.notNull(orderInfo, "订单不存在!");
        OrderItem orderIntem = orderItemMapper.selectOne(new LambdaQueryWrapper<OrderItem>().eq(OrderItem::getOrderId,orderId));
        OrderInfoDetailVo orderInfoDetailVo = new OrderInfoDetailVo();
        BeanUtils.copyProperties(orderInfo, orderInfoDetailVo);
        OrderLeaseDetailsDetailVo leaseDetailsDetailVo = new OrderLeaseDetailsDetailVo();
        OrderLeaseDetails orderLeaseDetails = orderLeaseDetailsMapper.selectOne(new LambdaQueryWrapper<OrderLeaseDetails>().eq(OrderLeaseDetails::getOrderId,orderId).last("limit 1"));
        AlipayAuthOrderFreeze alipayAuthOrderFreeze = alipayAuthOrderFreezeMapper.selectOne(new LambdaQueryWrapper<AlipayAuthOrderFreeze>().eq(AlipayAuthOrderFreeze::getOrderId,orderId).last("limit 1"));
        //待签约状态下 且当前订单尚未冻结押金 需根据用户风控信息 更新状态实际押金
        if(orderInfo.getStatus().equals(OrderEnum.SIGNED_ORDER.getCode()) && Objects.isNull(alipayAuthOrderFreeze)){
            //查询是否已存在免押订单
            int count = orderInfoMapper.countZeroDepositOrder(orderId,LikeFrontThreadLocal.getUserId());
            if(count==0) {
                RiskControl riskControl = riskControlMapper.selectOne(new LambdaQueryWrapper<RiskControl>().eq(RiskControl::getUserId, LikeFrontThreadLocal.getUserId()).last("limit 1"));
                if (Objects.nonNull(riskControl)) {
                    BigDecimal actDeposit = BigDecimal.valueOf(authOrderService.getByRiskScore(orderLeaseDetails.getDeposit(), riskControl.getRiskScore()));
                    if (!actDeposit.equals(orderLeaseDetails.getActualDeposit())) {
                        orderLeaseDetails.setActualDeposit(actDeposit);
                        orderLeaseDetailsMapper.updateById(orderLeaseDetails);
                    }
                }
            }
        }
        if(Objects.nonNull(orderLeaseDetails)){
            BeanUtils.copyProperties(orderLeaseDetails, leaseDetailsDetailVo);
            orderInfoDetailVo.setLeaseDetailsDetail(leaseDetailsDetailVo);
        }

        //todo
        List<OrderBillInfoVo> orderBillInfos = new  ArrayList<>();
        List<OrderBillInfo> orderBillInfoList = orderBillInfoMapper.selectList(new LambdaQueryWrapper<OrderBillInfo>().eq(OrderBillInfo::getOrderId,orderId));
        if(Objects.nonNull(orderBillInfoList)) {
            orderBillInfoList.forEach(orderBillInfo -> {
                OrderBillInfoVo billInfoVo = new OrderBillInfoVo();
                BeanUtils.copyProperties(orderBillInfo, billInfoVo);
                orderBillInfos.add(billInfoVo);
            });
        }
        orderInfoDetailVo.setOrderBillInfos(orderBillInfos);
        /*
          押金扣款记录
         */
        List<PreAuthorizationPaymentRecordListedVo> preAuthorizationPaymentRecordListedVos = new ArrayList<PreAuthorizationPaymentRecordListedVo>();
        List<PreAuthorizationPaymentRecord> preAuthorizationPaymentRecordList = preAuthorizationPaymentRecordMapper.selectList(new LambdaQueryWrapper<PreAuthorizationPaymentRecord>().eq(PreAuthorizationPaymentRecord::getOrderId,orderId));
        if(Objects.nonNull(preAuthorizationPaymentRecordList)) {
            preAuthorizationPaymentRecordList.forEach(preAuthorizationPaymentRecord -> {
                PreAuthorizationPaymentRecordListedVo preAuthorizationPaymentRecordListedVo = new PreAuthorizationPaymentRecordListedVo();
                BeanUtils.copyProperties(preAuthorizationPaymentRecord, preAuthorizationPaymentRecordListedVo);
                preAuthorizationPaymentRecordListedVos.add(preAuthorizationPaymentRecordListedVo);
            });
        }
        orderInfoDetailVo.setPreAuthorizationPaymentRecords(preAuthorizationPaymentRecordListedVos);

        ProductSpu productSpu =  productSpuMapper.selectById(orderIntem.getProductId());
        if(Objects.nonNull(productSpu)) {
            ProductSpuVo productSpuVo = new ProductSpuVo();
            BeanUtils.copyProperties(productSpu, productSpuVo);
            orderInfoDetailVo.setProductSpu(productSpuVo);
        }
        ProductSku productSku =  productSkuMapper.selectById(orderIntem.getProductSkuId());
        if(Objects.nonNull(productSku)) {
            ProductSkuVo productSkuVo = new ProductSkuVo();
            BeanUtils.copyProperties(productSku, productSkuVo);
            orderInfoDetailVo.setProductSku(productSkuVo);
        }
        return orderInfoDetailVo;
    }

    @Override
    public void cancel(Long orderId) throws AlipayApiException {
        OrderInfo orderInfo = orderInfoMapper.selectById(orderId);
        Assert.isFalse(!orderInfo.getStatus().equals(0) &&!orderInfo.getStatus().equals(1) , "当前状态不能进行取消操作!");
        Assert.notNull(orderInfo, "订单不存在!");

        orderInfo.setStatus(OrderEnum.CANCEL_ORDER.getCode());
        orderInfoMapper.updateById(orderInfo);
        //取消押金冻结授权
        authOrderService.cancelAuthOrderFreeze(orderId);
        //取消代扣签约
     // authOrderService.cancelUserAgreementRecord(orderId);
        LambdaQueryWrapper<OrderBillInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(OrderBillInfo::getOrderId,orderId);
        List<OrderBillInfo> orderBillInfoList = orderBillInfoMapper.selectList(new LambdaQueryWrapper<OrderBillInfo>().eq(OrderBillInfo::getOrderId,orderId));
        orderBillInfoList.forEach(orderBillInfo -> {
            orderBillInfo.setStatus(LeaseOrderStatusEnum.CANCELED.getCode());
            orderBillInfoMapper.updateById(orderBillInfo);
        });
    }

    @Override
    @Transactional
    public void finishPreOrder(Long orderId) {
        //todo 检查订单用户 订单状态

        //创建账单
        OrderInfo orderInfo = orderInfoMapper.selectById(orderId);
        OrderLeaseDetails orderLeaseDetails = orderLeaseDetailsMapper.selectOne(new LambdaQueryWrapper<OrderLeaseDetails>().eq(OrderLeaseDetails::getOrderId,orderId).last(" limit 1"));
        orderBillInfoService.createBillInfo(orderInfo.getId(),orderInfo.getDeptId(),orderInfo.getUserId(),orderLeaseDetails.getEachIssue(),orderLeaseDetails.getLeasePeriod());
        orderInfo.setStatus(RentOrderStatusEnum.READING_CAR.getCode());
        orderInfo.setPaymentTime(TimeUtils.nowDate());
        orderInfoMapper.updateById(orderInfo);
    }

    @Override
    @Transactional
    public Long addPreOrder(OrderCreateValidate orderCreateValidate) {
        Long userId = LikeFrontThreadLocal.getUserId();
        Store store = storeMapper.selectById(orderCreateValidate.getStoreId());
        org.springframework.util.Assert.notNull(store,"该门店不存在！");
        LeasingSchemeDetails leasingSchemeDetails = leasingSchemeDetailsMapper.selectById(orderCreateValidate.getLeasingSchemeDetailsId());
        Assert.notNull(leasingSchemeDetails,"该租赁计划不存在！");
        LeasingScheme leasingScheme = leasingSchemeMapper.selectById(leasingSchemeDetails.getSchemeId());

        //获取风控
        RiskControl riskControl = riskControlMapper.selectOne(new LambdaQueryWrapper<RiskControl>().eq(RiskControl::getUserId, LikeFrontThreadLocal.getUserId() )
                .last("limit 1").orderByDesc(RiskControl::getVersion));
        BigDecimal realAmount = leasingSchemeDetails.getDeposit();
        if(Objects.nonNull(riskControl)){
            //0-10免押金，10-30，押金50%，30以上100%押金
            realAmount = BigDecimal.valueOf(authOrderService.getByRiskScore(leasingSchemeDetails.getDeposit(), riskControl.getRiskScore()));
        }
        ProductSku productSku = productSkuMapper.selectOne(new LambdaQueryWrapper<ProductSku>()
                .eq(ProductSku::getProperties,orderCreateValidate.getProperties()).eq(ProductSku::getSpuId,leasingSchemeDetails.getSpuId()).last("limit 1"));
        Assert.notNull(productSku,"该车品sku不存在！");
        ProductSpu productSpu = productSpuMapper.selectOne(new LambdaQueryWrapper<ProductSpu>().eq(ProductSpu::getId,productSku.getSpuId()));


        //新增订单基础信息
        OrderInfo model = new OrderInfo();
        model.setOrderSn(generateOrderSn());
        model.setStoreId(store.getId());
        model.setDeptCode(store.getDeptCode());
        model.setUserId(Long.valueOf(userId));
        model.setStatus(OrderEnum.SIGNED_ORDER.getCode());
        model.setPayType(0);
        model.setOrderType(1);
        model.setSourceType(2);
        model.setNote(orderCreateValidate.getNote());
        model.setDeptId(store.getMerchantId());
        model.setDeptCode(store.getDeptCode());
        model.setCreateTime(new Date());
        orderInfoMapper.insert(model);

        //新增订单详细信息

        OrderItem orderItem = new OrderItem();
        orderItem.setProductPic(productSpu.getPicUrl());
        orderItem.setProductName(productSpu.getName());
        orderItem.setOrderId(model.getId());
        orderItem.setOrderSn(model.getOrderSn());
        orderItem.setProductId(productSpu.getId());
        orderItem.setProductSkuId(productSku.getId());
        orderItem.setProductQuantity(1L);
        orderItem.setProductCategoryId(productSpu.getCategoryId());
        orderItem.setProductAttr(productSku.getProperties());
        orderItem.setLeasingSchemeDetailsId(orderCreateValidate.getLeasingSchemeDetailsId());
        orderItemMapper.insert(orderItem);
        //新增租赁订单详情表
        OrderLeaseDetails  orderLeaseDetails = new OrderLeaseDetails();
        orderLeaseDetails.setOrderVehicleStatus(OrderVehicleStatusEnum.UN_DELIVER_ORDER.getCode());
        orderLeaseDetails.setOrderId(model.getId());
        orderLeaseDetails.setUserId(LikeFrontThreadLocal.getUserId());
        orderLeaseDetails.setServiceType(leasingScheme.getLeaseType());
        orderLeaseDetails.setLeaseType(leasingSchemeDetails.getLeaseType());
        orderLeaseDetails.setLeasePeriod(leasingSchemeDetails.getPeriodicity());
        orderLeaseDetails.setDownPayments(leasingSchemeDetails.getDownPayments());
        orderLeaseDetails.setDeposit(leasingSchemeDetails.getDeposit());
        orderLeaseDetails.setActualDeposit(realAmount);
        orderLeaseDetails.setEachIssue(leasingSchemeDetails.getAmountPeriod());
        orderLeaseDetails.setOtherExpenses(leasingSchemeDetails.getOtherExpenses());
        if(leasingSchemeDetails.getLeaseType().equals(1)) {
            orderLeaseDetails.setDueDate(DateUtils.addDays(DateUtils.addDays(new Date(),1), leasingSchemeDetails.getPeriodicity() * 30));
        }else if(leasingSchemeDetails.getLeaseType().equals(2)) {
            orderLeaseDetails.setDueDate(DateUtils.addDays(DateUtils.addDays(new Date(),1), leasingSchemeDetails.getPeriodicity() * 7));
        }if(leasingSchemeDetails.getLeaseType().equals(3)) {
            orderLeaseDetails.setDueDate( DateUtils.addDays(DateUtils.addDays(new Date(),1), leasingSchemeDetails.getPeriodicity()));
        }
        orderLeaseDetailsMapper.insert(orderLeaseDetails);

        //是否免押 是否已

        return model.getId();
    }

    @Override
    public OrderClueVo addOrderClue(OrderClueCreateValidate orderClueCreateValidate) {
        //新增订单基础信息
        OrderClue model = new OrderClue();
        BeanUtils.copyProperties(orderClueCreateValidate,model);
        model.setCreateTime(new Date());
        //设置默认部门
        model.setDeptId(1L);
        model.setDeptCode("1");
        orderClueMapper.insert(model);
        OrderClueVo orderClueVo = new OrderClueVo();
        BeanUtils.copyProperties(model,orderClueVo);

        return  orderClueVo;
    }

    @Override
    public OrderClueVo getOrderClueById(Long clueId) {
        OrderClue orderClue = orderClueMapper.selectById(clueId);
        OrderClueVo orderClueVo = new OrderClueVo();
        BeanUtils.copyProperties(orderClue,orderClueVo);
        return orderClueVo;
    }

    @Override
    public void refund() {

    }

    @Override
    public PageResult<CarOrderInfoListedVo> carOrderPage(Integer status, Integer type, PageValidate pageValidate) {
        Integer page  = pageValidate.getPageNo();
        Integer limit = pageValidate.getPageSize();
        Map params = new HashMap<>();
        params.put("userId", SaManager.getStpLogic("user").getLoginId());
        params.put("orderType", type);
        if(Objects.nonNull(status)){
            params.put("status",status);
        }
        IPage<CarOrderInfoListed> orderInfoList = orderInfoMapper.carOrderPage(new Page<>(page, limit), params);
        List<CarOrderInfoListedVo> orderInfoListedVos = new ArrayList<>();
        orderInfoList.getRecords().stream().forEach(carOrderInfoListed ->{
            CarOrderInfoListedVo carOrderInfoListedVo = new CarOrderInfoListedVo();
            BeanUtils.copyProperties(carOrderInfoListed,carOrderInfoListedVo);
            orderInfoListedVos.add(carOrderInfoListedVo);
        });
        return PageResult.iPageHandle(orderInfoList.getTotal(), orderInfoList.getCurrent(), orderInfoList.getSize(), orderInfoListedVos);
    }
    @Override
    public CarOrderDetailVo carOrderDetail(Long orderId) {
       CarOrderDetail carOrderDetail = orderInfoMapper.selectCarOrderDetailById(orderId);
       Assert.notNull(carOrderDetail,"订单数据不存在！");
       CarOrderDetailVo carOrderDetailVo = new CarOrderDetailVo();
       BeanUtils.copyProperties(carOrderDetail,carOrderDetailVo);
       return carOrderDetailVo;
    }

    @Override
    public void cancelCarOrder(Long orderId) throws AlipayApiException {
        //待支付、已支付  可以进行取消 状态 0待支付 7已完成 8已取消 9已支付 10 已退款
        OrderInfo orderInfo = orderInfoMapper.selectById(orderId);
        Assert.notNull(orderInfo,"该订单不存在！");
        Assert.isTrue(orderInfo.getStatus().equals(0)||orderInfo.getStatus().equals(9),"订单当前状态不能进行取消操作！");
        if(orderInfo.getStatus().equals(OrderEnum.PAID_ORDER.getCode())){
           //已支付 先进行退款操作
            refundByAli(orderInfo);
        }
        //更改订单状态为 已取消
        orderInfo.setStatus(OrderEnum.CANCEL_ORDER.getCode());
        orderInfoMapper.updateById(orderInfo);
    }
    @Override
    public void refundCarOrde(Long orderId) throws AlipayApiException {
        //待支付、已支付  可以进行取消 状态 0待支付 7已完成 8已取消 9已支付 10 已退款
        OrderInfo orderInfo = orderInfoMapper.selectById(orderId);
        Assert.notNull(orderInfo,"该订单不存在！");
        Assert.isTrue(orderInfo.getStatus().equals(9),"订单当前状态不能进行取消操作！");
        if(orderInfo.getStatus().equals(OrderEnum.PAID_ORDER.getCode())){
           //已支付 先进行退款操作
            refundByAli(orderInfo);
        }
        //更改订单状态为 已取消
        orderInfo.setStatus(OrderEnum.REFUNDED_ORDER.getCode());
        orderInfoMapper.updateById(orderInfo);
    }


    private void refundByAli(OrderInfo orderInfo) throws AlipayApiException {
        //退款
        AlipayTradeRefundModel alipayTradeRefundModel = new AlipayTradeRefundModel();
        alipayTradeRefundModel.setOutTradeNo(orderInfo.getOrderSn());
        alipayTradeRefundModel.setRefundAmount(orderInfo.getPayAmount().toString());
        AlipayTradeRefundResponse response = alipayTradeOrderService.refund(defaultAlipayClient,alipayTradeRefundModel);
        Assert.isTrue(response.isSuccess(),"退款失败！");
    }

    @Transactional
    @Override
    public String addDepositOrder(CarOrderCreateValidate carOrderCreateValidate) throws AlipayApiException {
        //创建订单
        Long userId = LikeFrontThreadLocal.getUserId();
        if(Objects.nonNull(carOrderCreateValidate.getStoreId())) {
            Store store = storeMapper.selectById(carOrderCreateValidate.getStoreId());
             Assert.notNull(store, "该门店不存在！");
        }
        ProductSpu productSpu = productSpuMapper.selectOne(new LambdaQueryWrapper<ProductSpu>().eq(ProductSpu::getId,carOrderCreateValidate.getSpuId()));
        if(Objects.nonNull(productSpu.getDeposit())){
            Assert.notNull(productSpu.getDeposit(),"该商品押金错误，请联系管理员进行修改！");
        }
        //新增订单基础信息
        OrderInfo model = new OrderInfo();
        OrderItem orderItem = new OrderItem();
        if(Objects.isNull(carOrderCreateValidate.getOrderId())) {
            model.setOrderSn(generateOrderSn());
            model.setStoreId(carOrderCreateValidate.getStoreId());
            model.setUserId(Long.valueOf(userId));
            model.setStatus(OrderEnum.TO_SIGNED.getCode());
            model.setPayType(0);
            model.setOrderType(productSpu.getType());
            model.setSourceType(2);
            model.setTotalAmount(productSpu.getDeposit());
            model.setPayAmount(productSpu.getDeposit().multiply(new BigDecimal(carOrderCreateValidate.getQuantity())));
            model.setArea(carOrderCreateValidate.getArea());
            model.setUserName(carOrderCreateValidate.getUserName());
            model.setMobile(carOrderCreateValidate.getMobile());
            orderInfoMapper.insert(model);

            CarBrand carBrand = carBrandMapper.selectById(productSpu.getBrandId());
            //新增订单详细信息
            orderItem.setProductPic(productSpu.getPicUrl());
            orderItem.setProductName(productSpu.getName() + "定金");
            if(Objects.nonNull(carBrand.getBrandName())) {
                orderItem.setProductBrand(carBrand.getBrandName());
            }
            orderItem.setOrderId(model.getId());
            orderItem.setOrderSn(model.getOrderSn());
            orderItem.setProductId(productSpu.getId());
            orderItem.setProductPrice(productSpu.getDeposit());
            orderItem.setProductQuantity(carOrderCreateValidate.getQuantity());
            orderItem.setProductCategoryId(productSpu.getCategoryId());
            orderItemMapper.insert(orderItem);
        }else {
            model = orderInfoMapper.selectById(carOrderCreateValidate.getOrderId());
            orderItem = orderItemMapper.selectOne(new LambdaQueryWrapper<OrderItem>().eq(OrderItem::getOrderId,model.getId()).last(" limit 1"));
        }
        //支付
         return createAlipayOrder(productSpu,model,orderItem);
    }


    private  String createAlipayOrder(ProductSpu productSpu,OrderInfo model,OrderItem orderItem) throws AlipayApiException {
        if(productSpu.getType().equals(1)){
            //零售，使用jsapi支付
            //小程序支付
            UserAuth userAuth = userAuthMapper.selectOne(new LambdaQueryWrapper<UserAuth>().eq(UserAuth::getUserId, LikeFrontThreadLocal.getUserId()).last("limit 1"));
            Assert.notNull(userAuth.getAlipayUserid(),"用户支付宝数据错误！");
            String notifyUrl = "https://www.yixiutong.cn/rtadmin/api/notify/callback.htm";
            // 构造请求参数以调用接口
            AlipayTradeCreateModel alipayTradeCreateModel = new AlipayTradeCreateModel();
            // 设置商户订单号
            alipayTradeCreateModel.setOutTradeNo(model.getOrderSn());
            // 设置产品码
            alipayTradeCreateModel.setProductCode("JSAPI_PAY");
            // 设置订单总金额
            alipayTradeCreateModel.setTotalAmount(model.getTotalAmount().toString());
            // 设置订单标题
            alipayTradeCreateModel.setSubject(orderItem.getProductName());
            // 设置订单附加信息
            alipayTradeCreateModel.setBuyerId(userAuth.getAlipayUserid());
            AlipayRoyaltyAccountInfo outAccountInfo = alipayRoyaltyAccountInfoMapper.selectById(2);

            //二级商户 default_settle_rule
            SubMerchant subMerchant = new SubMerchant();
            subMerchant.setMerchantId(outAccountInfo.getAccount());
            alipayTradeCreateModel.setSubMerchant(subMerchant);

            SettleInfo settleInfo = new SettleInfo();

            SettleDetailInfo settleDetailInfo = new SettleDetailInfo();
            settleDetailInfo.setAmount(alipayTradeCreateModel.getTotalAmount());
            settleDetailInfo.setTransInType("defaultSettle");
            List<SettleDetailInfo> settleDetailInfoList = new ArrayList<>();
            settleDetailInfoList.add(settleDetailInfo);
            settleInfo.setSettleDetailInfos(settleDetailInfoList);
            alipayTradeCreateModel.setSettleInfo(settleInfo);

            AlipayTradeCreateResponse response = alipayTradeOrderService.tradePay(defaultAlipayClient,alipayTradeCreateModel,notifyUrl);

            if (response.isSuccess()){
                AlipayTradePayInfo tradePayInfo = new AlipayTradePayInfo();
                tradePayInfo.setStatus(TradePayStatusEnum.PENDING_TRADE.getCode());
                tradePayInfo.setTradeNo(response.getTradeNo());
                tradePayInfo.setOutTradeNo(model.getOrderSn());
                tradePayInfo.setPayAmount(model.getPayAmount().toString());
                alipayTradePayInfoMapper.insert(tradePayInfo);
                System.out.println("调用成功");
            } else {
                System.out.println("调用失败");
            }
            return response.getTradeNo();
        } else if (productSpu.getType().equals(2)) {
            String notifyUrl = "https://www.yixiutong.cn/rtadmin/api/notify/callback.htm";
            String returnUrl = "https://www.yixiutong.cn/rt/car/index.html#/pages/packageA/carList/Result/index?result=1&id="+ model.getId();

            AlipayTradeWapPayModel alipayTradeWapPayModel = new AlipayTradeWapPayModel();
            alipayTradeWapPayModel.setOutTradeNo(model.getOrderSn());
            alipayTradeWapPayModel.setTotalAmount(model.getPayAmount().toString());
            alipayTradeWapPayModel.setSubject(orderItem.getProductName());
            alipayTradeWapPayModel.setProductCode("QUICK_WAP_WAY");

//            AlipayRoyaltyAccountInfo outAccountInfo = alipayRoyaltyAccountInfoMapper.selectById(2);
//
//            //二级商户 default_settle_rule
//            SubMerchant subMerchant = new SubMerchant();
//            subMerchant.setMerchantId(outAccountInfo.getAccount());
//            alipayTradePagePayModel.setSubMerchant(subMerchant);
//
//            SettleInfo settleInfo = new SettleInfo();
//
//            SettleDetailInfo settleDetailInfo = new SettleDetailInfo();
//            settleDetailInfo.setAmount(alipayTradePagePayModel.getTotalAmount());
//            settleDetailInfo.setTransInType("defaultSettle");
//            List<SettleDetailInfo> settleDetailInfoList = new ArrayList<>();
//            settleDetailInfoList.add(settleDetailInfo);
//            settleInfo.setSettleDetailInfos(settleDetailInfoList);
//            alipayTradePagePayModel.setSettleInfo(settleInfo);

            try {
                AlipayTradeWapPayResponse response = alipayTradeOrderService.tradePay(defaultAlipayWapClient, alipayTradeWapPayModel, notifyUrl, returnUrl);
                String pageRedirectionData = response.getBody();
                System.out.println(pageRedirectionData);

                if (response.isSuccess()) {
                    System.out.println("调用成功");
                } else {
                    System.out.println("调用失败");
                }
                //采购 使用手机网站支付
                return pageRedirectionData;
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return null;
    }
    public  String generateOrderSn() {
        String orderSn = "";
        while (true) {
            // 获取当前时间戳
            long timestamp = System.currentTimeMillis();
            // 获取当前日期
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
            String dateStr = dateFormat.format(System.currentTimeMillis());
            // 获取随机数
            Random random = new Random();
            int randomNum = random.nextInt(1000);
            // 组合订单编号
            orderSn = "O" + dateStr + randomNum + timestamp;
            OrderInfo orderInfo = orderInfoMapper.selectOne(new LambdaQueryWrapper<OrderInfo>()
                    .eq(OrderInfo::getOrderSn, orderSn )
                    .last("limit 1"));
            if (orderInfo == null) {
                break;
            }
            return orderSn;
        }
        return orderSn;
    }

}
